var layer;
var form;
var table;
var upload;
var laydate;
var treeSelect;
var tree;
var maxImg = 1;
var look = 0;

layui.use([ 'layer',  'form',  'table' ,  'laydate',  'upload' ,  'treeSelect',  'tree'],  function() {
	layer = layui.layer;
	form = layui.form;
	table = layui.table;
	upload = layui.upload;
	laydate = layui.laydate;
	treeSelect = layui.treeSelect;
	tree = layui.tree;

	// 日期初始化=============================================================================================
	laydate.render({elem : '#birthday', type:"date", format : "yyyy-MM-dd", trigger: 'click'});	
	laydate.render({elem : '#useDate', type:"datetime", format : "yyyy-MM-dd HH:mm:ss", trigger: 'click'});
	
	// 加载字典=============================================================================================
    getDictLabel("sex", "#sex", "sex", true);
    getDictLabel("sex", "#search_sex", "sex", false, 3);

    // 上传图片=============================================================================================
	upload.render({
	    elem: '#jzjzImg' 
	    , url: ''
	    , accept: 'images'
	    , exts: 'jpg|png|jpeg'
		, before: function(obj){
			this.url = (look == 0)?ctxPath+'upload/tempImage':'';
        }
	    , done: function(res){
		  	layer.msg(res.msg, {offset:"10%"})
		  	if(res.success){
		  		$("#data_form").find("input[name='img']").val(res.data);
				$("#jzjzImg").attr("src",  ctxPath + res.data+"?v="+Math.random());
				setTimeout(function () {
					$("#jzjzImg").attr("src",  ctxPath + res.data+"?v="+Math.random());
				}, 2000)
		  	}
	    }
	    , error: function(){
	    	if(look == 1){
	    		layer.msg("当前为查看状态", {offset:"100px"})
	    	}else{
	    		layer.msg("上传接口异常", {offset:"100px"})
	    	}
	    }
	});

	// 左侧树形=============================================================================================
	loadTreeLeft();

	// 执行一个 table 实例=============================================================================================
	table.render({
		elem : '#data_table', 
		id : 'data_table', 
		url : ctxPath+'sys/user/select',
		title : '数据列表',
		height:'full-120',
		//size:"sm", 
		page : true, 
		toolbar : "#toolberLeft", 
		cols : [[ 
			{type : 'checkbox', fixed : 'left'},  
			{field : 'id', title : '照片', align : 'center', width: '80', hide: setColumnHide("id"), 
				templet: function (d) {
	                var src = ctxPath+d.img+"?v="+Math.random();
	                return '<img width="45" style="border-radius: 5px;" height="45" id="img_'+d.id+'" src="'+src+'" onerror="errorImg(this)"/>';
				}
			},
			{field : 'name', title : '姓名', width: '150', align : 'center', hide: setColumnHide("name")}, 
			{field : 'sex', title : '性别', width: '80', sort : true, align : 'center',templet: function (d){return getDictText("sex",d.sex)}, hide: setColumnHide("sex")},
			{field : 'age', title : '年龄', width: '80', sort : true, align : 'center', hide: setColumnHide("age")}, 
			{field : 'userName', title : '登录名称', width: '150', sort : true, align : 'center', hide: setColumnHide("userName")},
			{field : 'useDate', title : '使用期限', width: '150', sort : true, align : 'center', hide: setColumnHide("useDate")}, 
			{field : 'phone', title : '手机号码', width: '150', sort : true, align : 'center', hide: setColumnHide("phone")}, 
			{field : 'idcard', title : '身份证号码', width: '150', sort : true, align : 'center', hide: setColumnHide("idcard"),
				templet: function (d) {
					return hidenNum(d.idcard, 3, 4);
				}
			},
			{field : 'rname', title : '角色名称', width: '150', sort : true, align : 'center', hide: setColumnHide("rname")}, 
			{field : 'oname', title : '项目/组织', width: '150', sort : true, align : 'center', hide: setColumnHide("oname")}, 
			{field : 'remarks', align : 'center', width: '150', title : '备注', hide: setColumnHide("remarks")}, 
			{fixed : isRight(), align : 'center', width: '180', title : '操作', toolbar : '#toolRow'} 
		]]
		,done:function(result,currPage,count){
	    }
	});
	
	// 头部左侧事件=============================================================================================
	table.on('toolbar(data_table)',  function(obj) {
		if (obj.event === 'search') {
			openWindowSearch('search_form', "条件搜索", '100%', 'auto', false, 0, false, false, null, 0.2, true)
		}else if(obj.event === 'add'){
        	var obj = {"birthday": getSysDate(1), "useDate": getSysDate(null, 70), "sex": 1}
			formData(obj, '添加用户');
			look = 0;
		}else if(obj.event === 'delete'){
            deleteBatch(table, 'data_table', "id", ctxPath+'sys/user/deleteBatch')
		}
	})
	
	// 行监听事件=============================================================================================
	table.on('tool(data_table)',  function(obj) {
		var data = obj.data;
		if (obj.event === 'del') {
			deleteRow(table, 'data_table', data, ctxPath+'sys/user/delete'+"?id="+data.id);
		} else if (obj.event === 'edit') {
			formData(data, "编辑用户");
			look = 0;
		} else if (obj.event === 'detail') {
			formData(data, "查看用户");
			look = 1;
		}
	});
	
	// 查询=============================================================================================
	form.on('submit(submitSearch)',  function(data) {
		reloadTable(table, 'data_table', data.field);
		return false;
	})
	
	// 提交=============================================================================================
	form.on('submit(submitForm)',  function(data) {
		saveData(table, 'data_table', data.field, data.field.id ? ctxPath+'sys/user/edit' : ctxPath+'sys/user/add', '#data_form');
		return false;
	})

	// 加载所有角色=============================================================================================
	loadDownSelector(ctxPath+"sys/role/selectAll", {}, 'rid,rid_search',  true,  'rid',  'rname');
	
})

/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 表单赋值
 */
function formData(data, title) {
	openWindowRB('data_form', title, '700px', '100%', false, 0, false, false, data, 0.2, false, function () {
		if(data && data.img){
			$("#jzjzImg").attr('src', ctxPath+(data.img?data.img:"images/head.png")+"?v="+Math.random());
		}else{
			$("#jzjzImg").attr('src', ctxPath+"images/head.png"+"?v="+Math.random());
		}
		loadTreeOrganization(data.oid);
	});
}

/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 获取所有项目-树形-下拉
 */
function loadTreeOrganization(id){
	$.get(ctxPath+"sys/organization/selectTreeAll", {}, function (result) {
		if (result.success){
			treeSelect.destroy('parentTree');
			// 参考：https://wujiawei0926.gitee.io/treeselect/docs/doc.html
			treeSelect.render({
				elem: '#parentTree',
				data:  '',
				list: result.data,
				type: 'get',
				placeholder: '请选择机构',
				search: true,
				style: {
					folder: {
						enable: false // 图标
					},
					line: {
						enable: true  // 线
					}
				},
				click: function(d){
					console.log(d);
				},
				success: function (d) {
					// 选中节点，根据id筛选
					treeSelect.checkNode('parentTree', id);
					// 刷新树结构
					treeSelect.refresh('parentTree');
				}
			});
		}
	})
}

/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 获取所有项目-树形-左侧
 */
function loadTreeLeft(){
	$.get(ctxPath+"sys/organization/selectTreeAll", {}, function (result) {
		if (result.success){
			tree.render({// https://www.layui.site/doc/modules/tree.html
				elem: '#leftTree'
				,data: result.data
				,onlyIconControl: true
				,click: function(obj){
					var id = obj.data.id;
					reloadTable(table, 'data_table', {"oid": id});
				}
			});
		}
	})
}










